<template>
  <Button
    size="small"
    :text="countState.isCounting ? countState.count + 's后重试' : '获取验证码'"
    :block="false"
    @click="runCountdown()"
    :disabled="countState.isCounting"
  >
  </Button>
</template>

<script>
import { onMounted, reactive, ref } from "vue";
import ctBlade from "ct_blade";
export default {
  name: "CountDown",
  props: {
    area: {
      type: String,
      default: "CN",
    },
    phone: {
      type: String,
      default: "",
    },
    count: {
      type: Number,
      default: 60,
    },
    countKey: {
      type: String,
      default: "ct_tick",
    },
  },
  setup(props, { emit }) {
    let countState = reactive({
      count: props.count,
      isCounting: false,
    });

    const fetchMsgCode = () => {
      return Promise.resolve();
    };

    const runCountdown = (e) => {
      if (!props.area) {
        $vm.$toast("电话国际区号不能为空!");
        return;
      }
      if (!props.phone) {
        $vm.$toast("电话号码不能为空!");
        return;
      }
      if (countState.isCounting) {
        return;
      }
      console.log("count down");
      fetchMsgCode({ area: props.area, phone: props.phone })
        .then((res) => {
          $vm.$toast(res.msg || "验证码已发送");
          if (res.data.vcode) {
            $vm.$toast("验证码: " + res.data.vcode);
          }

          ctBlade({
            key: props.countKey,
            cb: (res) => {
              countState.isCounting = !res.finish;
              countState.count = res.count;
            },
          });
          emit("success", res);
        })
        .catch((err) => {
          emit("failed", err);
        });
    };

    onMounted(() => {
      ctBlade({
        key: props.countKey,
        isCheck: true, //run countdown or checkout countdown (true means check)
        cb: (res) => {
          countState.isCounting = !res.finish;
          countState.count = res.count;
        },
      });
    });
    return { runCountdown, countState };
  },
};
</script>
<style lang="less" scoped>
</style>